package main
import (
         "fmt"
         "time" 
         "os"
         "strings"  
         "net/http"
         "io"
         "path/filepath"
        "github.com/gin-gonic/gin"
)


type PostData struct {
    ID           int    `json:"id"`
    FileUrl         string `json:"fileurl"`
    Hostname        string `json:"token"`
}



 
func  DownloadMP4File(url, destinationDir string) error {
        // 发起HTTP GET请求以下载文件
        response, err := http.Get(url)
        if err != nil {
                return err
        }
        defer response.Body.Close()

        // 获取文件名
        tokens := strings.Split(url, "/")
        filename := tokens[len(tokens)-1]

        // 创建目标文件
        destinationPath := filepath.Join(destinationDir, filename)
        file, err := os.Create(destinationPath)
        if err != nil {
                return err
        }
        defer file.Close()

        // 将HTTP响应的主体复制到目标文件
        _, err = io.Copy(file, response.Body)
        if err != nil {
                return err
        }

        //记录文件名
        return nil
}

func ApiServer() {

        r := gin.Default()
      
        r.POST("/submit", func(c *gin.Context) {
                var requestData  PostData 

                if err := c.ShouldBindJSON(&requestData); err != nil {
                        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
                        return
                }

                //  判断队列状态
                fmt.Println(time.Now(),"接受到的数据",requestData.FileUrl,requestData.Hostname )
                err :=  DownloadMP4File(requestData.FileUrl,"waterfile")
                if err  == nil {
                        fmt.Println(time.Now(),"下载完成", "远程主机", requestData.Hostname,"下载地址",requestData.FileUrl) 
                         c.String(200, "OK")
                }
                c.String(200, "OK")

        })

        r.Run("0.0.0.0:80") // 默认监听并在 0.0.0.0:8080 上启动服务
}




func main () {
      fmt.Println(time.Now())

      ApiServer()


}


